<template>
    <div class="admin-container">
        <div class="header-actions" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
            <h1>用户管理</h1>
            <el-button type="success" @click="showAddDialog">
                <el-icon><Plus /></el-icon>
                新增管理员
            </el-button>
        </div>

        <!-- 搜索框区域：仅保留账号搜索功能 -->
        <div class="search-container" style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center;">
            <el-input
                v-model="searchAcount"  
                placeholder="请输入账号搜索" 
                style="width: 400px;"  
                clearable 
                @keyup.enter="handleSearch"  
            />
            <el-button type="primary" @click="handleSearch">
                搜索
            </el-button>
            <el-button @click="handleReset">
                重置
            </el-button>
        </div>

        <!-- 用户表格 -->
        <el-table 
            :data="adminsList"  
            style="width: 100%; margin: 20px auto; border: 1px solid #eee;"
            border
            stripe
            :loading="tableLoading" 
        >
            <el-table-column prop="aid" label="管理员id" width="160" align="center" />
            <el-table-column prop="acount" label="管理员账号" width="300" align="center" />
            <el-table-column prop="aremarks" label="备注" width="300" align="center" />
            <el-table-column prop="permissionId" label="权限ID" width="160" align="center" />
            <el-table-column label="操作" width="280" align="center">
                <template #default="scope">
                    <el-button 
                        type="primary" 
                        size="small" 
                        @click="showUserDetail(scope.row)"
                        style="margin-right: 8px;"
                    >
                        查看详情
                    </el-button>
                    <el-button 
                        type="danger" 
                        size="small" 
                        icon="Delete" 
                        @click="handleDelete(scope.row.aid)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页功能 -->
        <div style="text-align: center; margin: 20px 0;">
            <el-pagination
                :page-size="params.pageSize"
                :total="params.recordCount"
                v-model:current-page="params.pageNum"
                @current-change="handlePageChange"
                layout="total,prev,pager,next"
                :disabled="tableLoading"
            />
        </div>

        <!-- 用户详情弹窗 -->
        <el-dialog 
            title="用户详情" 
            v-model="detailVisible" 
            width="50%"
            :close-on-click-modal="false"
        >
            <el-descriptions column="1" border>
                <el-descriptions-item label="用户ID">{{ currentUser.aid ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="用户账号">{{ currentUser.acount ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ currentUser.aremarks ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="权限ID">{{ currentUser.permissionId ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="注册时间">{{ formatTime(currentUser.aregtime) }}</el-descriptions-item>
                <el-descriptions-item label="用户状态">{{ currentUser.status === 1 ? '正常' : '禁用' }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 新增管理员弹窗：移除验证相关属性 -->
        <el-dialog 
            title="新增管理员" 
            v-model="addVisible" 
            width="50%"
            :close-on-click-modal="false"
        >
            <!-- 移除:rules和ref属性，简化表单 -->
            <el-form 
                :model="formData" 
                label-width="120px"
                style="margin-top: 20px;"
            >
                <!-- 移除prop属性，无需关联验证规则 -->
                <el-form-item label="管理员账号">
                    <el-input 
                        v-model="formData.acount" 
                        placeholder="请输入管理员账号"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="管理员密码">
                    <el-input 
                        v-model="formData.apwd" 
                        placeholder="请输入管理员密码"
                        type="password"
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="备注信息">
                    <el-input 
                        v-model="formData.aremarks" 
                        placeholder="请输入备注信息（可选）"
                        maxlength="200"
                    />
                </el-form-item>
                <el-form-item label="权限ID">
                    <el-input 
                        v-model.number="formData.permissionId" 
                        placeholder="请输入权限ID"
                        type="number"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="cancelAdd">取消</el-button>
                <el-button type="primary" @click="confirmAdd" :loading="addLoading">确认添加</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认弹窗 -->
        <el-dialog 
            title="删除确认" 
            v-model="deleteVisible" 
            width="30%"
            :close-on-click-modal="false"
        >
            <div>确定要删除 ID 为 <span style="color: #f56c6c; font-weight: 500;">{{ deleteAid }}</span> 的用户吗？删除后不可恢复！</div>
            <template #footer>
                <el-button @click="deleteVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">确认删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { Delete, Plus } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

// 导入接口
import { deleteById, queryPage } from '@/api/admin';
import { insertSave } from '@/api/admin';

// 搜索关键词
const searchAcount = ref('');

// 分页参数
const params = ref({
    pageNum: 1,
    pageSize: 5,
    recordCount: 0
});

// 页面状态：移除addFormRef（表单验证引用）
const adminsList = ref([]);
const detailVisible = ref(false);
const deleteVisible = ref(false);
const addVisible = ref(false);
const currentUser = ref({});
const deleteAid = ref('');
const tableLoading = ref(false);
const deleteLoading = ref(false);
const addLoading = ref(false);

// 新增表单数据
const formData = ref({
    acount: '',
    apwd: '',
    aremarks: '',
    permissionId: null
});

// 时间格式化函数
const formatTime = (isoTime) => {
    if (!isoTime) return '暂无数据';
    return dayjs(isoTime).format('YYYY-MM-DD HH:mm:ss');
};

// 核心查询逻辑
const queryUsers = () => {
    tableLoading.value = true;
    const searchKey = searchAcount.value.trim();
    const adminsQuery = searchKey ? { acount: searchKey } : null;

    // 区分普通分页/查询后分页
    const request = adminsQuery 
        ? queryPage(adminsQuery, params.value.pageNum, params.value.pageSize)
        : queryPage(params.value.pageNum, params.value.pageSize);

    request
        .then(data => {
            const resData = data || {};
            adminsList.value = resData.list || [];
            params.value.recordCount = resData.recordCount || 0;
        })
        .catch(err => {
            console.error('查询失败：', err);
            ElMessage.error(err.response?.data?.msg || '查询失败，请重试');
            adminsList.value = [];
            params.value.recordCount = 0;
        })
        .finally(() => {
            tableLoading.value = false;
        });
};

// 搜索按钮事件
const handleSearch = () => {
    params.value.pageNum = 1;
    queryUsers();
};

// 重置按钮事件
const handleReset = () => {
    searchAcount.value = '';
    params.value.pageNum = 1;
    queryUsers();
};

// 分页切换事件
const handlePageChange = (pageNum) => {
    params.value.pageNum = pageNum;
    queryUsers();
};

// 查看详情
const showUserDetail = (user) => {
    currentUser.value = JSON.parse(JSON.stringify(user));
    detailVisible.value = true;
};

// 删除用户相关
const handleDelete = (aid) => {
    if (!aid || typeof aid !== 'number' || aid < 1) {
        ElMessage.warning('无效的用户ID，无法删除');
        return;
    }
    deleteAid.value = aid;
    deleteVisible.value = true;
};

const confirmDelete = () => {
    deleteLoading.value = true;
    deleteById(deleteAid.value)
        .then(() => {
            ElMessage.success(`用户ID: ${deleteAid.value} 删除成功！`);
            deleteVisible.value = false;
            queryUsers();
        })
        .catch(err => {
            console.error('删除失败：', err);
            ElMessage.error(err.response?.data?.msg || `删除用户 ${deleteAid.value} 失败`);
        })
        .finally(() => {
            deleteLoading.value = false;
        });
};

// 新增管理员相关：移除表单验证逻辑
const showAddDialog = () => {
    // 仅清空表单数据，无需重置验证状态
    formData.value = {
        acount: '',
        apwd: '',
        aremarks: '',
        permissionId: null
    };
    addVisible.value = true;
};

const cancelAdd = () => {
    addVisible.value = false;
};

// 移除validate验证，直接调用接口
const confirmAdd = () => {
    // 简单非空判断（可选保留，也可完全删除）
    if (!formData.value.acount || !formData.value.apwd || !formData.value.permissionId) {
        ElMessage.warning('账号、密码、权限ID为必填项');
        return;
    }

    addLoading.value = true;
    insertSave(formData.value)
        .then(() => {
            ElMessage.success('管理员添加成功！');
            addVisible.value = false;
            queryUsers();
        })
        .catch(err => {
            console.error('添加失败：', err);
            ElMessage.error(err.response?.data?.msg || '添加管理员失败，请重试');
        })
        .finally(() => {
            addLoading.value = false;
        });
};

// 初始化加载数据
queryUsers();
</script>


  
  
  
  <style scoped>
  /* 容器核心样式：控制宽度+居中+背景 */
  .admin-container {
    max-width: 1400px; /* 限制最大宽度，避免大屏过宽 */
    width: 100%; /* 响应式宽度，小屏自适应 */
    margin: 0 auto;
    padding: 24px;
    background-color: #fff; /* 改为白色背景，更符合现代后台风格 */
    border-radius: 12px; /* 圆角增强质感 */
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); /* 轻微阴影，提升层次感 */
    font-family: "Inter", "Microsoft YaHei", sans-serif; /* 适配中英文的现代字体 */
  }
  
  /* 标题样式：居中+权重调整 */
  .admin-container h1 {
    text-align: center;
    font-size: 24px;
    font-weight: 600; /* 中等加粗，避免过粗 */
    color: #1f2937; /* 深灰，比纯黑更柔和 */
    margin: 0 0 28px; /* 只保留底部间距，精简冗余 */
  }
  
  /* 表格容器：控制宽度+居中 */
  .el-table {
    width: 100% !important; /* 覆盖 Element 默认，确保占满容器 */
    margin: 0 auto 24px !important; /* 底部留空，与分页分隔 */
    border-radius: 8px; /* 表格圆角（需配合 Element 配置） */
    overflow: hidden; /* 防止圆角被内容截断 */
  }
  
  /* 表格表头样式：加深背景+调整字体 */
  .el-table th {
    background-color: #f9fafb !important;
    font-weight: 500;
    color: #4b5563;
    font-size: 14px;
  }
  
  /* 表格行 hover 效果：柔和高亮 */
  .el-table__row:hover > td {
    background-color: #f3f4f6 !important;
  }
  
  /* 分页容器：居中+间距调整 */
  .el-pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 32px;
    font-size: 13px;
  }
  
  /* 弹窗标题样式：统一权重和颜色 */
  .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }
  
  /* 详情弹窗描述项：调整间距和对齐 */
  .el-descriptions {
    margin-top: 16px;
  }
  .el-descriptions-item {
    font-size: 14px;
    color: #374151;
    padding: 12px 16px !important; /* 增加内边距，提升可读性 */
  }
  .el-descriptions-item__label {
    font-weight: 500;
    color: #4b5563;
  }
  
  /* 按钮统一调整：缩小内边距，统一圆角 */
  .el-button--small {
    padding: 5px 12px !important;
    border-radius: 6px !important;
    font-size: 13px !important;
  }
  /* 操作列按钮间距：避免拥挤 */
  .el-table-column--operation .el-button {
    margin-right: 8px;
  }
  .el-table-column--operation .el-button:last-child {
    margin-right: 0;
  }
  
  /* 消息提示框：调整位置，避免遮挡 */
  .el-message {
    top: 60px !important;
  }
  .search-container {
    margin: 20px 0;
    display: flex;
    align-items: center;
  }
  </style>